/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.TreeMap;
import sirtet.GameAction;
import sirtet.Player;

/**
 * A player who uses keyboard as input.  It is necessary for this object
 * to be registered to a GUI component through <code>addKeyListener</code>.
 * @author guangwei.zhu
 */
public class KeyboardPlayer extends Player implements KeyListener {

    protected TreeMap commands = new TreeMap();

    public KeyboardPlayer(String playerID, String gametype) {
        super(playerID, gametype, true);
    }

    @SuppressWarnings({"unchecked"})
    public void registerKeyCommand(int keyCode, String command) {
        commands.put(keyCode, command);
    }

    public void unregisterKeyCommand(int keyCode) {
        commands.remove(keyCode);
    }

    @SuppressWarnings({"unchecked"})
    public void unregisterKeyCommand(String command) {
        while (commands.containsValue(command)) {
            for (Object key : commands.keySet()) {
                if (commands.get(key) == command) {
                    commands.remove(key);
                    break;
                }
            }
        }
    }

    public void keyTyped(KeyEvent evt) {
    }

    @SuppressWarnings({"unchecked"})
    public void keyPressed(KeyEvent evt) {  // Do Nothing
        int keyCode = evt.getKeyCode();
        Object command = commands.get(keyCode);

        if (command != null) {
            invokeAction(new GameAction(this.id(), (String) command));
        }
    }

    public void keyReleased(KeyEvent evt) { // Do Nothing
    }
}
